import { BASE_URL } from "../../utils/config";

interface IPageData {
  userInfo: {
    name: string;
    className?: string;
    avatar: string;
    classesId?: string;
  };
  showClassDialog: boolean;
  classList: Array<{
    id: string;
    className: string;
  }>;
  selectedClassId: string;
}

Page<IPageData>({
  data: {
    userInfo: {
      name: '',
      class: '',
      avatar: '/assets/icons/default-avatar.svg',
      classesId: ''
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    showClassDialog: false,
    classList: [],
    selectedClassId: ''
  },

  onLoad() {
    this.fetchUserInfo();
    this.fetchClassList();
  },

  chooseAvatar(e: any) {
    const { avatarUrl } = e.detail

    // 更新用户信息头像
    this.setData({
      'userInfo.avatar': avatarUrl,
      hasUserInfo: true
    });
    // 这里可以添加上传头像到服务器的逻辑
    const token = wx.getStorageSync('token');

    const uploadFilePromise = () => new Promise((resolve, reject) => {
      wx.uploadFile({
        url: `${BASE_URL}/file/upload`,
        filePath: avatarUrl,
        name: 'file',
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          const data = JSON.parse(res.data);
          console.log("upload res data", data);
          resolve(data.data.url);
        },
        fail: () => {
          wx.showToast({
            title: '上传头像失败',
            icon: 'error'
          });
          reject(new Error('上传头像失败'));
        }
      });
    });

    uploadFilePromise()
      .then(url => {
        this.setData({
          'userInfo.avatar': url
        });
        // 用户头像变更
        const token = wx.getStorageSync('token');
        wx.request({
          url: `${BASE_URL}/user/changeAvatar`,
          method: 'POST',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          data: {
            avatar: url
          },
          success: () => {
            wx.showToast({
              title: '头像更新成功',
              icon: 'success'
            });
          },
          fail: () => {
            wx.showToast({
              title: '头像更新失败',
              icon: 'error'
            });
          }
        });
      })
      .catch(err => {
        console.error(err);
      });
  },

  handleLogout() {
    wx.removeStorageSync('token');
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  navigateToPersonalInfo() {
    wx.navigateTo({
      url: '/pages/info/info'
    });
  },

  navigateToClassBinding() {
    if (this.data.userInfo.classesId) {
      wx.showToast({
        title: '您已绑定班级',
        icon: 'none'
      });
      return;
    }
    // this.fetchClassList();
    this.setData({
      showClassDialog: true
    });
  },

  fetchClassList() {
    const token = wx.getStorageSync('token');
    wx.request({
      url: `${BASE_URL}/student/classes/list`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res: any) => {
        const { data } = res.data;
        if (data) {
          this.setData({
            classList: data
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取班级列表失败',
          icon: 'error'
        });
      }
    });
  },

  handleClassSelect(e: any) {
    this.setData({
      selectedClassId: e.currentTarget.dataset.id
    });
  },

  handleClassConfirm() {
    if (!this.data.selectedClassId) {
      wx.showToast({
        title: '请选择班级',
        icon: 'none'
      });
      return;
    }

    const token = wx.getStorageSync('token');
    wx.request({
      url: `${BASE_URL}/student/bindClass`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: {
        classesId: this.data.selectedClassId
      },
      success: (res: any) => {
        wx.showToast({
          title: '绑定成功',
          icon: 'success'
        });
        this.setData({
          showClassDialog: false,
          'userInfo.classesId': this.data.selectedClassId
        });
        this.fetchUserInfo();
      },
      fail: () => {
        wx.showToast({
          title: '绑定失败',
          icon: 'error'
        });
      }
    });
  },

  handleClassCancel() {
    this.setData({
      showClassDialog: false,
      selectedClassId: ''
    });
  },

  navigateToFaceUpload() {
    wx.navigateTo({
      url: '/pages/faceRegister/faceRegister'
    });
  },

  navigateToLeave() {
    wx.navigateTo({
      url: '/pages/leave/leave'
    });
  },

  navigateToLeaveList() {
    wx.navigateTo({
      url: '/pages/leaveList/leaveList'
    });
  },

  navigateToRecord() {
    wx.navigateTo({
      url: '/pages/record/record'
    });
  },

  navigateToIndex() {
    wx.navigateTo({
      url: '/pages/index/index'
    });
  },

  fetchUserInfo() {
    const token = wx.getStorageSync('token');
    wx.request({
      url: `${BASE_URL}/user/info`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res: any) => {
        const { data } = res.data;
        if (data) {
          // 从classList中找到对应的班级名称
          const matchedClass = this.data.classList.find(item => item.id === data.classesId);
          this.setData({
            userInfo: {
              name: data.name || '',
              avatar: data.avatar || '',
              classesId: data.classesId || '',
              className: matchedClass ? matchedClass.className : ''
            }
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取信息失败',
          icon: 'error'
        });
      }
    });
  },
  lifetimes: {
    attached() {
      // 在组件实例进入页面节点树时执行
    },
  }
});